package com.cqhz.quwan.ui.mine

import android.Manifest
import android.app.Activity
import android.text.SpannableString
import android.text.Spanned
import android.text.SpannedString
import android.text.style.AbsoluteSizeSpan
import com.blankj.utilcode.util.StringUtils
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.ExpertInfoBean
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.mvp.mine.ExpertCertificationContract
import com.cqhz.quwan.mvp.mine.ExpertCertificationPresenter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.util.GlideImageLoader
import com.cqhz.quwan.util.UploadUtil
import com.cqhz.quwan.util.isContainChinese
import com.cqhz.quwan.util.setLoadImage
import com.tbruyelle.rxpermissions2.RxPermissions
import com.yancy.gallerypick.config.GalleryConfig
import com.yancy.gallerypick.config.GalleryPick
import com.yancy.gallerypick.inter.IHandlerCallBack
import kotlinx.android.synthetic.main.activity_expert_certification.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject

/**
 * 专家认证
 * Created by Guojing on 2018/10/29.
 */
class ExpertCertificationActivity : GoBackActivity(), ExpertCertificationContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var expertCertificationPresenter: ExpertCertificationPresenter
    private var loginBean: LoginBean? = null
    private var headPortrait: String = ""
    private var rxPermissions: RxPermissions? = null

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "专家认证"
    }

    override fun layout(): Int {
        return R.layout.activity_expert_certification
    }

    override fun beforeInitView() {
        super.beforeInitView()
        rxPermissions = RxPermissions(this)
    }

    override fun initView() {
        expertCertificationPresenter.attachView(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
            expertCertificationPresenter.getExpertInfo(loginBean!!.userId!!)
        }

        // 头像
        action_avatar.setOnClickListener {
            // 调用拍照模块
            rxPermissions!!.requestEachCombined(Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe { permission ->
                        if (permission.granted) {
                            selectImages()
                        }
                    }
        }
        action_commit.setOnClickListener {
            var nickname = et_nickname.text.toString().trim()
            var introduce = et_introduce.text.toString().trim()

            if (nickname.isEmpty()) {
                showToast("请输入昵称")
                return@setOnClickListener
            }

            if (introduce.isEmpty()) {
                introduce = "稳如哈马比，一起红！"
            }

            expertCertificationPresenter.expertAuth(loginBean!!.userId!!, nickname, headPortrait, introduce)// 保存
        }
    }

    override fun setExpertInfo(bean: ExpertInfoBean) {
        // 暂时使用
        setHeadUrl(bean.head_portrait)
        iv_level.setImageResource(when (bean.rank) {
            1 -> R.drawable.details_level_1
            2 -> R.drawable.details_level_2
            3 -> R.drawable.details_level_3
            else -> R.drawable.details_level_1
        })
        iv_level_nick.setImageResource(when (bean.rank) {
            1 -> R.drawable.rz_ic_silver
            2 -> R.drawable.rz_ic_gold
            3 -> R.drawable.rz_ic_platinum
            else -> R.drawable.rz_ic_silver
        })
        et_nickname.setText(bean.nick)
        val ss = SpannableString(if (bean.rank < 1) "设置后不可更改" else "")//定义hint的值
        val ass = AbsoluteSizeSpan(18, true)// 设置字体大小 true表示单位是sp
        ss.setSpan(ass, 0, ss.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        et_nickname.hint = SpannedString(ss)
        et_nickname.isEnabled = bean.rank < 1
        et_nickname.isFocusable = bean.rank < 1
        et_nickname.isFocusableInTouchMode = bean.rank < 1

        et_introduce.setText(bean.introduce)
    }

    override fun setHeadUrl(url: String?) {
        headPortrait = if (StringUtils.isEmpty(url)) "http://h5.zhanguo.fun/td/img/img_tx.png" else url!!
        // 用户头像
        action_avatar.setLoadImage(this, headPortrait, R.drawable.rz_ic_default)
    }

    override fun commitSuccess() {
        showToast("提交成功")
        setResult(Activity.RESULT_OK)
        finish()
    }

    /**
     * 选择上传的图片
     */
    private fun selectImages() {
        val galleryConfig = GalleryConfig.Builder()
                .imageLoader(GlideImageLoader())// ImageLoader 加载框架（必填）
                .iHandlerCallBack(object : IHandlerCallBack {
                    override fun onStart() {

                    }

                    override fun onSuccess(files: List<String>) {
                        UploadUtil.uploadImages(files, object : UploadUtil.CallResult<String> {
                            override fun onResponse(data: String) {
                                if (data.isContainChinese()) {
                                    showToast(data)
                                } else {
                                    setHeadUrl(data)
                                }
                            }

                            override fun onFailure(data: String) {
                                showToast("保存失败，请重试")
                            }
                        })

//                        val partList = ArrayList<MultipartBody.Part>()
//                        for (i in files.indices) {
//                            val file = File(files[i])
//
//                            val builder = MultipartBody.Builder()
//                                    .setType(MultipartBody.FORM)// 表单类型
//
//                            val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
//
//                            builder.addFormDataPart("file", file.name, requestBody)// file 后台接收图片流的参数名
//
//                            partList.add(builder.build().part(i))
//                        }
//
//                        expertCertificationPresenter.updateHead(partList)
                    }

                    override fun onCancel() {

                    }

                    override fun onFinish() {

                    }

                    override fun onError() {

                    }
                })// 监听接口（必填）
                .multiSelect(true, 1)
                .provider(KeyContract.FILE_PROVIDER)// provider (必填)
                .crop(true, 1f, 1f, 500, 500)// 配置裁剪功能的参数，默认裁剪比例 1:1
                .isShowCamera(true)// 是否显示相机按钮  默认：false
                .filePath(KeyContract.FILE_PATH)// 图片存放路径
                .build()
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this)// 开启图片选择器
    }

    override fun onDestroy() {
        super.onDestroy()
        expertCertificationPresenter.detachView()
    }
}
